/*
 * UserManager.cpp
 *
 *  Created on: 2013-1-29
 *      Author: Dspark
 */
#include "UserManager.h"


UserManager::UserManager(QWidget *parent)
:QDialog(parent), label("查询条件"), searchButton("搜索"), addUserButton("添加新用户"),
 lockButton("停用选中用户"), modifyButton("修改用户信息"), modifyDialog(this), table(100, 6)
{
	qDebug() << "enter UserManager::UserManager(QWidget *parent)";
	connect(&addUserButton, SIGNAL(clicked()), this, SLOT(slt_addMode()));
	connect(&modifyButton, SIGNAL(clicked()), this, SLOT(slt_modifyMode()));
	connect(&lockButton, SIGNAL(clicked()), this, SLOT(slt_lock()));
	connect(&modifyDialog, SIGNAL(sig_modifyOrAdd(const int &, const int &, const QString &, const QString &, const int &, const bool &, const QString &)),
			this, SLOT(slt_modifyOrAdd(const int &, const int &, const QString &, const QString &, const int &, const bool &, const QString &)));
	connect(&searchButton, SIGNAL(clicked()), this, SLOT(search()));
	connect(&table, SIGNAL(cellClicked(int, int)), this, SLOT(slt_buttonEnabled(int, int)));
	QStringList tableName;
	tableName << "序号" << "用户名" << "登录名" << "用户类型" << "是否停用" << "创建日期";
	table.setHorizontalHeaderLabels(tableName);
	table.setSelectionBehavior(QAbstractItemView::SelectRows);
	table.setSelectionMode(QAbstractItemView::SingleSelection);
	table.setEditTriggers(QAbstractItemView::NoEditTriggers);
	table.setColumnHidden(0, true);
	lockButton.setDisabled(true);
	modifyButton.setDisabled(true);
	db = Dao.getDateBase();
/*	db = QSqlDatabase::addDatabase("QMYSQL");
	db.setHostName("localhost");
	db.setDatabaseName("gemdale");
	db.setUserName("root");
	db.setPassword("sasa");
	if (!db.open())
		qDebug() << "Failed to connect to root mysql admin";
	else
		qDebug() << "Succeed to connect to mysql.";*/
	QHBoxLayout *topLayout = new QHBoxLayout;
	topLayout->addWidget(&label);
	topLayout->addWidget(&lineEdit);
	topLayout->addWidget(&searchButton);
	topLayout->addStretch();
	topLayout->addWidget(&addUserButton);
	topLayout->addWidget(&modifyButton);
	topLayout->addWidget(&lockButton);
	QVBoxLayout *mainLayout = new QVBoxLayout;
	mainLayout->addLayout(topLayout);
	mainLayout->addWidget(&table);
	this->setLayout(mainLayout);
	setWindowTitle("人员管理");


}

void UserManager::search()
{
	qDebug() << "enter void UserManager::search()";
	table.clearContents();
	QSqlQuery query(db);
	if(lineEdit.text() != 0)
	{
		query.prepare("SELECT * FROM user WHERE name LIKE :Name ORDER BY CONVERT(name USING gbk)");
		query.bindValue(":Name", "%"+lineEdit.text()+"%");
	}
	else
	{
		query.prepare("SELECT * FROM user ORDER BY CONVERT(name USING gbk)");
	}
	query.exec();
	QSqlRecord record = query.record();
	int idx_id = record.indexOf("id");
	int idx_name = record.indexOf("name");
	int idx_signName = record.indexOf("signName");
	int idx_type = record.indexOf("type");
	int idx_locked = record.indexOf("locked");
	int idx_createDate = record.indexOf("createDate");
	int i = 0;
	while(query.next())
	{
		table.setItem(i, 0, new QTableWidgetItem(query.value(idx_id).toString()));
		table.setItem(i, 1, new QTableWidgetItem(query.value(idx_name).toString()));
		table.setItem(i, 2, new QTableWidgetItem(query.value(idx_signName).toString()));
		table.setItem(i, 3, new QTableWidgetItem((query.value(idx_type).toInt() == (User::SaleManager)) ? "营销经理" : "区域领导"));
		QCheckBox *lock = new QCheckBox;
		lock->setChecked(query.value(idx_locked).toBool());
		lock->setDisabled(true);
		table.setCellWidget(i, 4, lock);
		table.setItem(i, 5, new QTableWidgetItem(query.value(idx_createDate).toString()));
		if(++i > table.rowCount())
			table.insertRow(table.rowCount());
//		qDebug() << query.value(0).toString() << query.value(1).toString()
//				<< query.value(2).toString() << query.value(3).toString();
	}
}

void UserManager::slt_addMode()
{
	qDebug() << "enter void UserManager::slt_addMode()";
	modifyButton.setDisabled(true);
	lockButton.setDisabled(true);
	modifyDialog.setMode(ModifyUser::addMode);
	modifyDialog.setUi();
	modifyDialog.show();
}

void UserManager::slt_modifyMode()
{
	qDebug() << "enter void UserManager::slt_modifyMode()";
	lockButton.setDisabled(true);
	if(table.item(table.currentRow(), 0) == 0)
	{
		qDebug() << "UserManager::slt_modifyMode() return because table.item(table.currentRow(), 0) == ";
		return;
	}
	int idCurrent = table.item(table.currentRow(), 0)->text().toInt();
	qDebug() << "table.currentRow() = " << table.currentRow() << "; idCurrent = " << idCurrent;
	QSqlQuery query(db);
	query.prepare("SELECT * FROM user WHERE id=:ID");
	query.bindValue(":ID", idCurrent);
	query.exec();
	modifyDialog.setMode(ModifyUser::modifyMode);
	QSqlRecord record = query.record();
	int idx_name = record.indexOf("name");
	int idx_signName = record.indexOf("signName");
	int idx_type = record.indexOf("type");
	int idx_locked = record.indexOf("locked");
	int idx_password = record.indexOf("password");
	if(query.next())
	{
		modifyDialog.setUi(idCurrent, query.value(idx_name).toString(), query.value(idx_signName).toString(),
				query.value(idx_type).toInt(), query.value(idx_locked).toBool(), query.value(idx_password).toString());
	}
	modifyDialog.show();
}

void UserManager::slt_modifyOrAdd(const int &mode, const int &id, const QString &name, const QString &signName,
			const int &type, const bool &locked, const QString &password)
{
	qDebug() << "enter UserManager::slt_modifyOrAdd" << "; id = " << id << "; name is " << name
			<< "; signname is " << signName << "; type is " << type << "; locked is " << locked
			<< "; passeord is " << password;

	QSqlQuery query(db);
	if(mode == ModifyUser::modifyMode)
	{
		QSqlQuery queryTest(db);
		queryTest.prepare("SELECT signName FROM user WHERE id<>:Id");
		queryTest.bindValue(":Id", id);
		queryTest.exec();
		bool signNameExisted = false;
		while(queryTest.next())
		{
			if(queryTest.value(0).toString() == signName)
			{
				signNameExisted = true;
				break;
			}
		}
		qDebug() << "signNameExisted = " << signNameExisted;
		if(signName == 0 || signNameExisted)
		{
			int r = QMessageBox::information(this, tr("登录名错误"),
					tr("你输入的登录名已存在或者为空！"), QMessageBox::Yes);
			if(r == QMessageBox::Yes)
			{
				modifyDialog.show();
				return ;
			}
		}


		qDebug() << "modifying......" << "locked = " << locked;
		query.prepare("UPDATE user SET name=:Name, signName=:SignName, type=:Type, locked=:Locked, password=:Password WHERE id=:Id");
		query.bindValue(":Id", id);
	}
	if(mode == ModifyUser::addMode)
	{
		QSqlQuery queryTest(db);
		queryTest.exec("SELECT signName FROM user");
		bool signNameExisted = false;
		while(queryTest.next())
		{
			if(queryTest.value(0).toString() == signName)
			{
				signNameExisted = true;
				break;
			}
		}
		qDebug() << "signNameExisted = " << signNameExisted;
		if(signName == 0 || signNameExisted)
		{
			int r = QMessageBox::information(this, tr("登录名错误"),
					tr("你输入的登录名已存在或者为空！"), QMessageBox::Yes);
			if(r == QMessageBox::Yes)
			{
				modifyDialog.show();
				return;
			}
		}


		QDate timeNow;
		QString timeStr(timeNow.currentDate().toString("yyyyMMdd"));
		qDebug() << "insert......timeNow is " << timeStr;
		query.prepare("INSERT INTO user (name, signName, password, locked, type, createDate)"
				"VALUES (:Name, :SignName, :Password, :Locked, :Type, :CreateDate)");
		query.bindValue(":CreateDate", timeStr);
	}
	query.bindValue(":Name", name);
	query.bindValue(":SignName", signName);
	query.bindValue(":Type", type);
	query.bindValue(":Locked", locked);
	query.bindValue(":Password", password);

	query.exec();
	search();
}

void UserManager::slt_buttonEnabled(int row, int column)
{
//	qDebug() << "enter void UserManager::buttonEnabled(int row, int column)";
	modifyButton.setEnabled(true);
	addUserButton.setEnabled(true);
	lockButton.setEnabled(true);
}

void UserManager::slt_lock()
{
	qDebug() << "enter UserManager::slt_lock()";
	if(table.item(table.currentRow(), 0) == 0)
		return;
	int idCurrent = table.item(table.currentRow(), 0)->text().toInt();
	qDebug() << "table.currentRow() = " << table.currentRow() << "; idCurrent = " << idCurrent;
	QSqlQuery query(db);
	query.prepare("UPDATE user SET locked=1 WHERE id=:ID");
//	query.bindValue(":Lock", 1);
	query.bindValue(":ID", idCurrent);
	query.exec();
	search();
}

UserManager::~UserManager() {
	// TODO Auto-generated destructor stub
}

